package com.contract.commonlib.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.lxj.xpopup.core.BasePopupView;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author zhengjun
 * @desc 工具类
 * @create at 2018/8/14 11:40
 */

public class CommonUtils {

    public static boolean isPopShow(BasePopupView popupView) {
        return popupView != null && popupView.isShow();
    }

    public static boolean isEmptyList(List list) {
        return list == null || list.size() <= 0;
    }

    public static Bitmap decodeResourceLowMemory(Resources res, int id) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            Bitmap bitmap = BitmapFactory.decodeResource(res, id, options);
            return bitmap;
        } catch (OutOfMemoryError memoryError) {
            clearMemoryCache();
        }
        return null;

    }

    public static void clearMemoryCache() {
        try {
            Glide.get(Utils.getApp()).clearMemory();
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //跳转到应用在应用市场的详情页面进行评分
    public static void goMarketDetail(Context context) {
        try {
            Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "您的手机没有安装Android应用市场", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * @desc 把list集合转为字符创
     * @author zhengjun
     * @created at 2018/6/5 11:00
     */
    public static String getListValue(List<String> list) {
        if (list != null && list.size() > 0) {
            String value = "";
            for (String city : list) {
                if (TextUtils.isEmpty(value)) {
                    value = city;
                } else {
                    value = String.format("%S,%S", value, city);
                }
            }
            return value;
        }
        return "";
    }

    /**
     * @param value 需要转换的值
     * @param regex 转换的规则即是以什么符合为分隔符
     * @desc 将字符串转化为list集合
     * @author zhengjun
     * @created at 2018/6/5 10:59
     */
    public static List<String> getStringToList(String value, String regex) {
        if (TextUtils.isEmpty(value)) {
            return new ArrayList<>();
        }
        List<String> list = java.util.Arrays.asList(value.split(regex));
        return list;
    }

    /**
     * 根据文件大小自动转化为KB, MB, GB
     *
     * @param target_size
     */
    public static String formatSize(Context context, long target_size) {
        return Formatter.formatFileSize(context, target_size);
    }


    /**
     * 返回app运行状态
     *
     * @param context     一个context
     * @param packageName 要判断应用的包名
     * @return int 1:前台 2:后台 0:不存在
     */
    public static int isAppAlive(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> listInfos = activityManager
                .getRunningTasks(20);
        // 判断程序是否在栈顶
        if (listInfos.get(0).topActivity.getPackageName().equals(packageName)) {
            return 1;
        } else {
            // 判断程序是否在栈里
            for (ActivityManager.RunningTaskInfo info : listInfos) {
                if (info.topActivity.getPackageName().equals(packageName)) {
                    return 2;
                }
            }
            return 0;// 栈里找不到，返回0
        }
    }

    public static int getDimension(int dimenId) {
        return Utils.getApp().getResources().getDimensionPixelSize(dimenId);
    }

    public static int getColor(int colorId) {
        return Utils.getApp().getResources().getColor(colorId);
    }


    public static void setMarginLeft(View view, int leftMargin) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
            marginLayoutParams.leftMargin = leftMargin;
            view.setLayoutParams(layoutParams);
        }
    }

    public static void setMarginRight(View view, int rightMargin) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
            marginLayoutParams.rightMargin = rightMargin;
            view.setLayoutParams(layoutParams);
        }
    }


    public static void setMarginTop(View view, int topMargin) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
            marginLayoutParams.topMargin = topMargin;
            view.setLayoutParams(layoutParams);
        }
    }

    public static void setMarginBottom(View view, int bottomMargin) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
            marginLayoutParams.bottomMargin = bottomMargin;
            view.setLayoutParams(layoutParams);
        }
    }

    public static void setPaddinTop(View view, int leftPadding, int topMargin, int rightMargin, int bottomPadding) {
        view.setPadding(leftPadding, topMargin, rightMargin, bottomPadding);
    }

    public static void clearCalendarHour(Calendar calendar) {
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    public static String secondToHMSTime(long time) {
        return secondToHMSTime(time, "%02d:%02d:%02d");
    }


    public static String secondToHMSTime(long time, String format) {
        int day = (int) (time / 24 / 3600);
        time = time % (24 * 3600);
        int hour = (int) (time / 3600);
        int minute = (int) (time / 60 % 60);
        int second = (int) (time % 60);
        return String.format(format, hour + day * 24, minute, second);
    }

    public static boolean isToday(long time) {
        return isSameOfDay(time, System.currentTimeMillis());
    }

    public static boolean isSameOfDay(long time1, long time2) {
        Date date = new Date(time1);
        Date date2 = new Date(time2);
        Calendar calendar = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar.setTime(date);//给calendar赋值
        int y1 = calendar.get(Calendar.YEAR);//获取年份
        int d1 = calendar.get(Calendar.DAY_OF_YEAR);//获取年中第几天
        calendar2.setTime(date2);

        int y2 = calendar2.get(Calendar.YEAR);
        int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
        return y1 == y2 && d1 == d2;
    }

    public static String getTodayStr() {
        Date date = new Date(System.currentTimeMillis());
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public static String getYestodyStr(int i, String dayFormat) {
        Date date = new Date();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat(dayFormat);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        String dateString = "";
        try {
            calendar.add(Calendar.DATE, i);//把日期往后增加一天.整数往后推,负数往前移动
            date = calendar.getTime(); //这个时间就是日期往后推一天的结果
            dateString = formatter.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateString;
    }

    public static boolean compareString(String startValue, String endValue) {
        return new BigDecimal(startValue).compareTo(new BigDecimal(endValue)) >= 0;
    }

    public static String multiplyString(String startValue, String endValue) {
        return new BigDecimal(startValue).multiply(new BigDecimal(endValue)).toPlainString();
    }
    private static long touchTime = 0;
    private static long touchTimeDialogTask = 0;
    private static final long WAIT_TIME = 2000;
    private static final long WAIT_TIME_DIALOG_TASK = 1000 * 60 * 60 * 2;
    public static boolean exitApp(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTimeDialogTask) >= WAIT_TIME_DIALOG_TASK) {
                touchTimeDialogTask = currentTime;
                return true;
            } else if ((currentTime - touchTime) >= WAIT_TIME) {
                ToastUtils.showShort("再按一次退出");
                touchTime = currentTime;
                return true;
            }
        }
        return false;
    }

    public static String getUrlLastValue(String url){
        int index = url.lastIndexOf("/");
        return url.substring(index + 1);
        //boolean matches = url.matches("[^/]+(?!.*/)");
    }
}
